$(function() {
    let res = null;
    let usermsg = JSON.parse(sessionStorage.getItem("usermsg"));
    if (usermsg !== null) {
        writeUserMsg();
    }

    function writeUserMsg() {
        $("#username").val(usermsg.username);
        $("#password_u").val(usermsg.password);

    }

    function login() {
        let options = {
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
            }
        }
        let data = {
            username: $("#username").val(),
            password: $("#password").val(),
        }
        axios.post("http://127.0.0.1:8888/users/login", formatData(data), options)
            .then(response => {
                console.log(formatData(data));
                console.log(response);
                console.log(response.data);
                res = response.data;
                if (res.code === 0) {
                    error(res);
                } else if (res.code === 1) {
                    success(res);
                }
            })
    }

    $("#user_login2").click(() => login());

    function error(res) {
        alert("抱歉登录失败 : " + res.message);
    }

    function success(res) {
        alert("恭喜登陆成功！");
        location.href = "./index.html";
        cookie("Token", res.token);
        cookie("ID", res.user.id);
    }
})


const btna5 = document.getElementById("btna5");
let username = document.getElementById("mobile");
let password = document.getElementById("password");
let rpassword = document.getElementById("confirm_password");
let nickname = document.getElementById("nickname");
console.log(btna5, username, password, rpassword, nickname);

btna5.onclick = async function() {
    // 发起请求先明确几件事情 :
    // - 1. 请求路径 ;
    // - 2. 请求方式;
    // - 3. 请求参数 ;
    let url = "http://127.0.0.1:8888/users/register";
    let options = {
        method: "POST",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded"
        },
        body: `username=${username.value}&password=${password.value}&rpassword=${rpassword.value}&nickname=${nickname.value}`
    };

    let response = await fetch(url, options);
    console.log(response);
    let data = await response.json();

    console.log(data);
    // 注册结束之后我们应该跳转到登录页面;
    if (data.code === 1) {
        alert("注册成功，马上为您跳转到登录页面");
        setTimeout(function() {
            location.href = "login.html";
        }, 2000)
    } else {
        alert(data.message);
    }
}